package com.eversec.msg.service.impl;

import com.eversec.msg.component.Producer;
import com.eversec.msg.service.ActivemqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.*;

/**
 * Created by eversec on 2018/3/2.
 */
@Service
public class ActivemqServiceImpl implements ActivemqService {

       @Autowired // 也可以注入JmsTemplate，JmsMessagingTemplate对JmsTemplate进行了封装
       private JmsTemplate jmsTemplate;

    	@Autowired
	    private Producer producer;

       // 发送消息，destination是发送到的队列，message是待发送的消息
        public void sendMessage(Destination destination, final String message){
            producer.sendMessage(destination, message);
         }


    /**
     * attention:
     * Details：接收消息，同时回复消息
     * @author chhliu
     * 创建时间：2016-7-28 下午2:39:45
     * @param destination
     * @return
     */
    @Override
    public String receiveMessage(Destination destination, Destination replyDestination) {
        /**
         * 接收消息队列中的消息
         */
        Message message = jmsTemplate.receive(destination);
        try {
            /**
             * 此处为了更好的容错性，可以使用instanceof来判断下消息类型
             */
            if(message instanceof TextMessage){
                String receiveMessage =  ((TextMessage) message).getText();
                System.out.println("收到生产者的消息:"+receiveMessage);
                /**
                 * 收到消息之后，将回复报文放到回复队列里面去
                 */
                jmsTemplate.send(replyDestination, new MessageCreator() {

                    @Override
                    public Message createMessage(Session session) throws JMSException {
                        return session.createTextMessage("消费者已经收到生产者的消息了，这是一条确认报文!");
                    }
                });
                return receiveMessage;
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return "";
    }
}
